package com.shanghai.shanghaielectric.UI.chart;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.shanghai.shanghaielectric.Model.THD_ChartModel;
import com.shanghai.shanghaielectric.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;
import shanghaielectric_lib.MyEventBus.EventBus_showCells;
import shanghaielectric_lib.Utils.LogUtil;

/**
 * 数据界面
 */
public class ChartFragment_THD extends Fragment implements View.OnClickListener {
    List<Button> bt_list;
    int bt_pressed_id = 0;
    String[] y_titles = new String[]{"网侧电流A相", "网侧电流B相", "网侧电流C相", "负载电流A相", "负载电流B相", "负载电流C相"};
    public Context mcontext;
    ColumnChartView chart;
    public View dataView;
    Button bt_thd_1, bt_thd_2, bt_thd_3, bt_thd_4, bt_thd_5, bt_thd_6;

    int thd_index = 0;
    List<Map<Integer, Float>> list_values = new ArrayList<>();
    List list_x = new ArrayList();
    List list_y = new ArrayList();

    double[] values_temp_thd = new double[]{0, 0, 0, 0, 0, 0};


//    UpdateDao.UpdateTHDListener updateTHDListener = new UpdateDao.UpdateTHDListener() {
//        @Override
    @Subscribe
        public void update(THD_ChartModel thd_chartModel) {
//            LogUtil.e("yyyyy", "yyyyyyy---" + thd_chartModel.getThd_index());

            for (int i = 0; i < 6; i++) {
                values_temp_thd[0] = thd_chartModel.getThd_data_1();
                values_temp_thd[1] = thd_chartModel.getThd_data_2();
                values_temp_thd[2] = thd_chartModel.getThd_data_3();
                values_temp_thd[3] = thd_chartModel.getThd_data_4();
                values_temp_thd[4] = thd_chartModel.getThd_data_5();
                values_temp_thd[5] = thd_chartModel.getThd_data_6();
            }

            if (thd_chartModel.getThd_index() == 0) {

            } else if (thd_chartModel.getThd_index() > 0) {
                for (int i = 0; i < 6; i++) {
                    list_values.get(i).put(thd_chartModel.getThd_index(), (float) values_temp_thd[i]);
                }
            }
//取值

            List <Integer>list_keys_temp = new ArrayList();
            List <Float>list_values_temp = new ArrayList();
            //遍历map中的键

            for (Integer key : list_values.get(bt_pressed_id).keySet()) {
                list_keys_temp.add(key);
//                System.out.println("lllllKey = " + key);
            }
            for (Float value : list_values.get(bt_pressed_id).values()) {
                list_values_temp.add(value);
//                System.out.println("lllllvalue = " + value);
            }
            if (list_keys_temp.size() > 0 && list_values_temp.size() > 0) {
                generateData(list_keys_temp, list_values_temp, y_titles[bt_pressed_id]);

            }
            generateData(list_keys_temp, list_values_temp, y_titles[bt_pressed_id]);

        }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        System.out.println("Data____onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("Data____onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        System.out.println("Data____onCreateView");
        dataView = inflater.inflate(R.layout.data_fragment, container,
                false);
        mcontext = this.getActivity().getApplicationContext();

        EventBus.getDefault().register(this);
        initView();
        initData();
        initchart();
        initListener();
        return dataView;
    }

    private void initData() {


        list_values.add(new ArrayMap<Integer, Float>());
        list_values.add(new ArrayMap<Integer, Float>());
        list_values.add(new ArrayMap<Integer, Float>());
        list_values.add(new ArrayMap<Integer, Float>());
        list_values.add(new ArrayMap<Integer, Float>());
        list_values.add(new ArrayMap<Integer, Float>());

    }
    private void initListener() {
//        todo 通知接口====
//        ReceiveDataHelper.setTHDDataListener(updateTHDListener);
        bt_thd_1.setOnClickListener(this);
        bt_thd_2.setOnClickListener(this);
        bt_thd_3.setOnClickListener(this);
        bt_thd_4.setOnClickListener(this);
        bt_thd_5.setOnClickListener(this);
        bt_thd_6.setOnClickListener(this);
    }

    private void initchart() {
//        final List<Integer> list_x = new ArrayList();
//        final List<Integer> list_y = new ArrayList();
//        final List<Integer> list_y_2 = new ArrayList();

        chart = (ColumnChartView) dataView.findViewById(R.id.chart);
        chart.setZoomEnabled(false);//设置是否支持缩放
//		chart.setOnValueTouchListener(ColumnChartOnValueSelectListener touchListener);//为图表设置值得触摸事件
        chart.setInteractive(false);//设置图表是否可以与用户互动
        chart.setValueSelectionEnabled(true);//设置图表数据是否选中进行显示
//		chart.setColumnChartData();//为图表设置数据，数据类型为ColumnChartData
//        for (int i = 0; i < 50; i++) {
//            list_x.add(i + 1);
//            list_y.add(i + 1);
//            list_y_2.add(50 - i);
//        }

//        generateData(list_x, list_y, "");
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//
//                    try {
//                        generateData(list_x, list_y, "");
//                        Thread.sleep(1000);
//                        generateData(list_x, list_y_2, "");
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//
//                }
//            }
//        }).start();

    }

    private void generateData(List<Integer> list, List<Float> list_y, String y_title) {
        //每个集合显示几条柱子
        int numSubcolumns = 1;
        //显示多少个集合
        int numColumns = list.size();
        //保存所有的柱子
        List<Column> columns = new ArrayList<Column>();
        //保存每个竹子的值
        List<SubcolumnValue> values;//YYYYYYYYYYYYY


        List<AxisValue> axisXValues = new ArrayList<AxisValue>();
        //对每个集合的柱子进行遍历
        for (int i = 0; i < numColumns; ++i) {

            values = new ArrayList<SubcolumnValue>();
            //循环所有柱子（list）
            for (int j = 0; j < numSubcolumns; ++j) {
                //创建一个柱子，然后设置值和颜色，并添加到list中
                values.add(new SubcolumnValue(list_y.get(i), ChartUtils.pickColor()));
                //设置X轴的柱子所对应的属性名称
                axisXValues.add(new AxisValue(i).setLabel(list.get(i) + ""));
            }
            //将每个属性的拥有的柱子，添加到Column中
            Column column = new Column(values);
            //是否显示每个柱子的Lable
            column.setHasLabels(true);
            //设置每个柱子的Lable是否选中，为false，表示不用选中，一直显示在柱子上
            column.setHasLabelsOnlyForSelected(false);
            //将每个属性得列全部添加到List中
            columns.add(column);
        }
        //设置Columns添加到Data中
        ColumnChartData data = new ColumnChartData(columns);
        //设置X轴显示在底部，并且显示每个属性的Lable，字体颜色为黑色，X轴的名字为“学历”，每个柱子的Lable斜着显示，距离X轴的距离为8
        data.setAxisXBottom(new Axis(axisXValues).setHasLines(false).setTextColor(Color.BLACK).setName("").setHasTiltedLabels(false).setMaxLabelChars(8).setTextSize(20));
        //设置Y轴                                                                                                                            Y轴线
        data.setAxisYLeft(new Axis().setHasLines(false).setName(y_title).setTextColor(Color.BLACK).setMaxLabelChars(5).setTextSize(25).setHasSeparationLine(true).setHasLines(false));
        //最后将所有值显示在View中
        chart.setColumnChartData(data);
    }

    private void initView() {
        bt_list=new ArrayList<>();
        bt_thd_1 = (Button) dataView.findViewById(R.id.bt_thd_1);
        bt_thd_2 = (Button) dataView.findViewById(R.id.bt_thd_2);
        bt_thd_3 = (Button) dataView.findViewById(R.id.bt_thd_3);
        bt_thd_4 = (Button) dataView.findViewById(R.id.bt_thd_4);
        bt_thd_5 = (Button) dataView.findViewById(R.id.bt_thd_5);
        bt_thd_6 = (Button) dataView.findViewById(R.id.bt_thd_6);

        bt_list.add(bt_thd_1);
        bt_list.add(bt_thd_2);
        bt_list.add(bt_thd_3);
        bt_list.add(bt_thd_4);
        bt_list.add(bt_thd_5);
        bt_list.add(bt_thd_6);
        bt_list.get(0).setBackgroundResource(R.drawable.btn_gray);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("Data____onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("Data____onStart");
    }


    @Override
    public void onResume() {
        super.onResume();

        System.out.println("Data____onResume");
    }

    @Override
    public void onPause() {
        super.onPause();

        System.out.println("Data____onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("Data____onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("Data____onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        System.out.println("Data____onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("Data____onDetach");
    }

    @Override
    public void onClick(View v) {
        for (int i = 0; i <bt_list.size() ; i++) {
            if (bt_list.get(i).getId()==v.getId()){
                refreshButtonBackground(i);
                bt_pressed_id=i;
            }
        }

    }
    private void refreshButtonBackground(int i) {
        for (int j = 0; j < bt_list.size(); j++) {
            if (j == i) {
                bt_list.get(j).setBackgroundResource(R.drawable.btn_gray);
            } else {
                bt_list.get(j).setBackgroundResource(R.drawable.btn_default);
            }
        }
    }

}
